package com.xdu.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.xdu.common.R;
import com.xdu.domain.Staff;
import com.xdu.service.StaffService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;

@Slf4j
@RestController
@RequestMapping("/staff")
public class StaffController {
    @Autowired
    private StaffService staffService;

    /**
     * 员工登陆
     * @param request
     * @param staff
     * @return
     */
    @PostMapping("/login")
    public R<Staff> login(HttpServletRequest request, @RequestBody Staff staff){
        //1、将页面提交的密码password进行md5加密处理
        String password = staff.getPassword();
        password = DigestUtils.md5DigestAsHex(password.getBytes());
        //2、根据页面提交的用户名username查询数据库
        LambdaQueryWrapper<Staff> queryWrapper = new LambdaQueryWrapper<>();//添加查询条件
        queryWrapper.eq(Staff::getName,staff.getName());//等值查询条件
        Staff staff1 = staffService.getOne(queryWrapper);
        //3:没有查询到返回登陆失败结果
        if(null == staff1){
            return R.error("登陆失败");
        }
        //4:密码比对，如果不一致则返回登陆失败
        if(!password.equals(staff1.getPassword())){
            return R.error("登陆失败");
        }
        //5:如果员工状态为禁用，返回“员工已被禁用”
        if(staff1.getStatus()!=1){
            return R.error("当前账号被禁用");
        }
        //6、登录成功，将员工id存入Session并返回登录成功结果
        request.getSession().setAttribute("staff",staff1.getId());
        return R.success(staff1);
    }

    /**
     * 员工退出
     * @param request
     * @return
     */
    @PostMapping("/logout")
    public R<String> logout(HttpServletRequest request){
        //1:清除session的信息
        request.getSession().removeAttribute("staff");
        //2:返回结果
        return R.success("退出成功");
    }
}
